package cn.com.inossem.activity;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.util.Base64;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.foxykeep.datadroid.requestmanager.Request;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import Decoder.BASE64Encoder;
import cn.com.inossem.base.RequestActivity;
import cn.com.inossem.model.AddBaGuaInfoBean;
import cn.com.inossem.requestmanager.WooRequestFactory;
import cn.com.inossem.utils.ActivityStackControlUtil;
import cn.com.inossem.utils.ToastUtil;
import cn.com.inossem.utils.Utils;
import cn.com.inossem.utils.view.BaGuaBiaoQianDialogFragment;
import cn.com.inossem.utils.view.BaGuaBiaoQianDialogFragment.biaoqianListener;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * 八卦发布
 * <p>
 * <p>
 * detailed comment
 *
 * @author szc 2015-8-24
 * @see
 * @since 1.0
 */
@RuntimePermissions
public class BaGuaFabuActivity extends RequestActivity implements
		biaoqianListener {

	RelativeLayout buttomlayout;
	ImageView fabu, back, zhaopian;

	BaGuaBiaoQianDialogFragment dialog;

	LinearLayout biaoqianlayout, piclayout;

	EditText fabuedit;

	TextView submit, textnum, huaming, text1, text2;
	public static AddBaGuaInfoBean bean;

	private List<String> biaoqianlist;
	private List<String> piclist;

	RelativeLayout fabukuang;

	boolean buttomkuang = false;
	private Uri localUri;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.main_tab_layout);
		getInfo();
		initView();

	}

	@Override
	public void onDestroy() {
		ActivityStackControlUtil.remove(this);
		super.onDestroy();
	}

	private void initView() {
		bean = new AddBaGuaInfoBean();
		biaoqianlist = new ArrayList<String>();
		piclist = new ArrayList<String>();

		submit = (TextView) this.findViewById(R.id.submit);
		submit.setOnClickListener(this);

		textnum = (TextView) this.findViewById(R.id.textnum);
		fabuedit = (EditText) this.findViewById(R.id.fabuedit);
		fabuedit.addTextChangedListener(new TextWatcher() {
			private CharSequence temp;
			private int selectionStart;
			private int selectionEnd;
			private int num = 140;

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
			                          int count) {
				temp = s;
				// System.out.println("s=" + s);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
			                              int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				int number = s.length();
				textnum.setText(number + "/" + num);
				selectionStart = fabuedit.getSelectionStart();
				selectionEnd = fabuedit.getSelectionEnd();
				// System.out.println("start="+selectionStart+",end="+selectionEnd);
				if (temp.length() > num) {
					s.delete(selectionStart - 1, selectionEnd);
					int tempSelection = selectionStart;
					fabuedit.setText(s);
					fabuedit.setSelection(tempSelection);// 设置光标在最后
				}
			}
		});

		back = (ImageView) this.findViewById(R.id.back);
		back.setOnClickListener(this);

		buttomlayout = (RelativeLayout) this.findViewById(R.id.buttomlayout);

		fabu = (ImageView) this.findViewById(R.id.fabu);
		fabu.setOnClickListener(this);

		zhaopian = (ImageView) this.findViewById(R.id.zhaopian);
		zhaopian.setOnClickListener(this);

		biaoqianlayout = (LinearLayout) this.findViewById(R.id.biaoqianlayout);
		piclayout = (LinearLayout) this.findViewById(R.id.piclayout);

		fabukuang = (RelativeLayout) this.findViewById(R.id.fabukuang);

		huaming = (TextView) this.findViewById(R.id.huaming);
		huaming.setOnClickListener(this);

		text1 = (TextView) this.findViewById(R.id.text1);
		text1.setOnClickListener(this);
		text2 = (TextView) this.findViewById(R.id.text2);
		text2.setOnClickListener(this);

		String textstr = name;

		text1.setText("花名：" + textstr);
	}

	@Override
	public Request getInitialRequest() {
		return null;
	}

	@Override
	public void onRequestSucess(Request request, Bundle bundle) {
		if (bundle.containsKey(WooRequestFactory.BUNDLE_EXTRA_UPDATESUCCESS)) {
			if (bundle.getInt(WooRequestFactory.BUNDLE_EXTRA_UPDATESUCCESS) == 1) {
				Toast.makeText(this, "发布成功!", Toast.LENGTH_LONG).show();
				setResult(2);
				finish();
			} else {
				Toast.makeText(this, "发布失败!", Toast.LENGTH_LONG).show();
			}
		}
	}

	@Override
	public void onRequestError(int exceptionType) {

	}

	public int getContentViewId() {
		return R.layout.baguafabu_layout;

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.text1:
				getInfo();
				huaming.setText("显示花名");
				buttomkuang = false;
				fabukuang.setVisibility(View.GONE);
				break;
			case R.id.text2:
				name = "匿名";
				huaming.setText("隐藏花名");
				buttomkuang = false;
				fabukuang.setVisibility(View.GONE);
				break;
			case R.id.huaming:
				if (buttomkuang) {
					buttomkuang = false;
					fabukuang.setVisibility(View.GONE);
				} else {
					buttomkuang = true;
					fabukuang.setVisibility(View.VISIBLE);
				}
				break;
			case R.id.back:
				finish();
				break;
			case R.id.fabu:
				if (biaoqianlist.size() < 3) {
					dialog = new BaGuaBiaoQianDialogFragment();
					dialog.show(getFragmentManager(), "loginDialog");
				} else {
					Toast.makeText(this, "标签只能3个！", Toast.LENGTH_LONG).show();
				}
				break;
			case R.id.zhaopian:
				showDialog(COMMON_DIALOG);
				break;
			case R.id.submit:
				bean = new AddBaGuaInfoBean();
				if (!fabuedit.getText().toString().equals("")) {
					bean.setText(fabuedit.getText().toString());
					if (biaoqianlist.size() > 0) {
						String biaoqiantext = biaoqianlist.get(0);
						for (int i = 1; i < biaoqianlist.size(); i++) {
							biaoqiantext += "," + biaoqianlist.get(i);
						}
						bean.setKeys(biaoqiantext);
					}
					if (piclist.size() > 0) {
						String pictext = piclist.get(0);
						for (int i = 1; i < piclist.size(); i++) {
							pictext += "," + piclist.get(i);
						}
						bean.setPics(pictext);
					}
					bean.setName(name);
					bean.setIcon(picname);
					launchRequest(WooRequestFactory.addBagua());
				} else {
					Toast.makeText(this, "内容不能为空！", Toast.LENGTH_LONG).show();
				}
				break;
			default:
				break;
		}
	}

	@Override
	public void onLoginInputComplete(String edit) {
		// TODO Auto-generated method stub
		if (edit.length() > 5) {
			Toast.makeText(this, "标签不能大于5个字！", Toast.LENGTH_LONG).show();
		} else if (!edit.equals("")) {
			// 确定
			addBiaoqian(edit);
			if (dialog != null) {
				dialog.dismiss();
				dialog = null;
			}
		} else {
			if (dialog != null) {
				dialog.dismiss();
				dialog = null;
			}
		}
	}

	public void addpic(final String str, Bitmap bitmap) {
		piclist.add(str);
		ImageView img = new ImageView(this);
		img.setLayoutParams(new LayoutParams(Utils.dip2px(this, 80), Utils
				.dip2px(this, 80)));
		// img.setBackgroundDrawable(new BitmapDrawable(stringtoBitmap(str)));
		img.setBackgroundDrawable(new BitmapDrawable(bitmap));
		// img.setImageBitmap(bitmap);
		img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				piclist.remove(str);
				System.out.println("piclist.size():" + piclist.size());
				piclayout.removeView(arg0);

			}
		});

		piclayout.addView(img);
	}

	public void addBiaoqian(final String str) {
		biaoqianlist.add(str);
		TextView tv = new TextView(this);
		tv.setPadding(20, 20, 20, 20);
		tv.setText(str);
		tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				biaoqianlist.remove(str);
				biaoqianlayout.removeView(arg0);

				// if (biaoqianlist.size() == 0) {
				// biaoqianlayout.removeAllViews();
				// } else {
				// biaoqianlayout.removeView(arg0);
				// }
			}
		});

		biaoqianlayout.addView(tv);
	}

	final int COMMON_DIALOG = 1;

	protected Dialog onCreateDialog(int id) { // 重写onCreateDialog方法
		Dialog dialog = null; // 声明一个Dialog对象用于返回
		switch (id) { // 对id进行判断
			case COMMON_DIALOG:
				Builder b = new AlertDialog.Builder(this);
				// b.setIcon(); //设置对话框的图标
				b.setTitle(R.string.dialogTitle); // 设置对话框的标题
				b.setMessage(R.string.fangshi); // 设置对话框的显示内容
				b.setPositiveButton( // 添加按钮
						R.string.xiangce, new DialogInterface.OnClickListener() { // 为按钮添加监听器
							public void onClick(DialogInterface dialog, int which) {
								BaGuaFabuActivityPermissionsDispatcher.setViewChocieWithCheck(BaGuaFabuActivity.this);
							}
						});
				b.setNegativeButton( // 添加按钮
						R.string.paiyizhang, new DialogInterface.OnClickListener() { // 为按钮添加监听器
							public void onClick(DialogInterface dialog, int which) {
								BaGuaFabuActivityPermissionsDispatcher.setPaizhaoChocieWithCheck(BaGuaFabuActivity.this);
							}
						});
				dialog = b.create(); // 生成Dialog对象
				break;
			default:
				break;
		}
		return dialog; // 返回生成Dialog的对象
	}

	@NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
	public void setViewChocie() {
		Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
		startActivityForResult(intent, 0);
	}

	@NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
	public void setPaizhaoChocie() {
		localUri = getTempFile("paizhao.jpg");
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			Intent mIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			mIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
			mIntent.putExtra(MediaStore.EXTRA_OUTPUT, localUri);
			startActivityForResult(mIntent, CAMERA_WITH_DATA);
		} else {
			ToastUtil.show(this, "没有储存卡");
		}
	}

	private Uri getTempFile(String picName) {
		File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/sapapp");
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File f = new File(dir, picName);
		if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
			return Uri.fromFile(f);
		} else {
			return FileProvider.getUriForFile(BaGuaFabuActivity.this, getPackageName() + ".fileprovider", f);
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		BaGuaFabuActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
	}

	BitmapDrawable drawable;
	Bitmap cameraBitmap;
	private static final int PHOTO_PICKED_WITH_DATA = 3021;
	private static final int CAMERA_WITH_DATA = 3023;

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		cameraBitmap = null;
		System.out.println(requestCode + "resultCode:" + resultCode);

		switch (requestCode) {
			case 0:

				if (resultCode != -1)
					return;
				Uri originalUri = data.getData();
				if (originalUri != null) {
					// cameraBitmap =
					// MediaStore.Images.Media.getBitmap(resolver,
					// originalUri);
					String[] filePathColumn = {MediaStore.Images.Media.DATA};

					Cursor cursor = getContentResolver().query(originalUri,
							filePathColumn, null, null, null);
					cursor.moveToFirst();
					int column_index = cursor.getColumnIndex(filePathColumn[0]);
					String picturePath = cursor.getString(column_index);
					cursor.close();
					// cameraBitmap = BitmapFactory.decodeFile(picturePath);
					cameraBitmap = ratio(BitmapFactory.decodeFile(picturePath),
							800f, 800f);
					String imagestr = bitmaptoString(cameraBitmap);
					// Bitmap bit = stringtoBitmap(imagestr);

					addpic(imagestr, cameraBitmap);
				}
				break;
			case CAMERA_WITH_DATA:
				File f = new File(Environment.getExternalStorageDirectory().getPath() + "/sapapp/paizhao.jpg");
				try {
					Uri u = Uri.parse(android.provider.MediaStore.Images.Media
							.insertImage(getContentResolver(), f.getAbsolutePath(),
									null, null));
					String[] filePathColumn = {MediaStore.Images.Media.DATA};

					Cursor cursor = getContentResolver().query(u, filePathColumn,
							null, null, null);
					cursor.moveToFirst();
					int column_index = cursor.getColumnIndex(filePathColumn[0]);
					String picturePath = cursor.getString(column_index);
					cursor.close();
					cameraBitmap = ratio(BitmapFactory.decodeFile(picturePath),
							800, 800);
					String imagestr = bitmaptoString(cameraBitmap);

					addpic(imagestr, cameraBitmap);
					// u就是拍摄获得的原始图片的uri，剩下的你想干神马坏事请便……
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			case PHOTO_PICKED_WITH_DATA:
				cameraBitmap = data.getParcelableExtra("data");
				if (cameraBitmap != null) {
					// imagestr = bitmaptoString(cameraBitmap);
					// Utils.messageInfo.userInfo.setImageData(imagestr);

					// touxiang.setBackgroundDrawable(new BitmapDrawable(Utils
					// .toRoundCorner(cameraBitmap, 50)));
				}
				break;

			default:
				break;
		}
	}

	public String bitmaptoString(Bitmap bitmap) {
		// 将Bitmap转换成字符串
		String string = null;
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.JPEG, 100, bStream);
		byte[] bytes = bStream.toByteArray();
		string = Base64.encodeToString(bytes, Base64.DEFAULT);
		return string;
	}

	public Bitmap stringtoBitmap(String string) {
		// 将字符串转换成Bitmap类型
		Bitmap bitmap = null;
		try {
			byte[] bitmapArray;
			bitmapArray = Base64.decode(string, Base64.DEFAULT);
			bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
					bitmapArray.length);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bitmap;
	}

	/**
	 * base64转为bitmap
	 *
	 * @param base64Data
	 * @return
	 */
	public static Bitmap base64ToBitmap(String base64Data) {
		byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
		return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
	}

	protected void doCropPhoto(Bitmap data) {
		Intent intent = getCropImageIntent(data);
		startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
	}

	public static Intent getCropImageIntent(Bitmap data) {
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		intent.setType("image/*");
		intent.putExtra("data", data);
		intent.putExtra("return-data", true);
		return intent;
	}

	String name;
	String picname;

	private void getInfo() {
		SharedPreferences settings = this
				.getSharedPreferences("shared_file", 0);
		// 第二个参数为如果SharedPreferences中没有保存就赋一个默认值
		name = settings.getString("name", "许愿的猪");
		picname = settings.getString("picname", "h1");
	}

	// 图片转化成base64字符串
	public static String GetImageStr(String imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try {
			in = new FileInputStream(imgFile);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data);// 返回Base64编码过的字节数组字符串
	}

	/**
	 * Compress image by size, this will modify image width/height. Used to get
	 * thumbnail
	 *
	 * @param image
	 * @param pixelW target pixel of width
	 * @param pixelH target pixel of height
	 * @return
	 */
	public Bitmap ratio(Bitmap image, float pixelW, float pixelH) {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, os);
		if (os.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
			os.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, 100, os);// 这里压缩50%，把压缩后的数据存放到baos中
		}
		ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		newOpts.inPreferredConfig = Config.RGB_565;
		Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		float hh = pixelH;// 设置高度为240f时，可以明显看到图片缩小了
		float ww = pixelW;// 设置宽度为120f，可以明显看到图片缩小了
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		is = new ByteArrayInputStream(os.toByteArray());
		bitmap = BitmapFactory.decodeStream(is, null, newOpts);
		// 压缩好比例大小后再进行质量压缩
		// return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大，反而耗资源，删除
		return bitmap;
	}

	@Override
	public void onConfigurationChanged(Configuration config) {
		super.onConfigurationChanged(config);
	}
}
